﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;
using RestSharp;

namespace XamarinAndroidSample.DroidMVP.Util
{
    public class ClientUtil
    {
        public const string host = "192.168.1.114";
        public const string port = "51516";
        public const string url = "http://" + host + ":" + port + "/api/";
        internal static RestClient GetRestClient(string url)
        {
            var restClient = new RestClient(url)
            {
                Timeout = 5000,
                ReadWriteTimeout = 5000
            };
            return restClient;
        }


        public static async Task GetAsync<T>(string url, Dictionary<string, string> _params, Action<T> success, Action<string> error)
        {
            try
            {
                var client = GetRestClient(url);
                RestRequest request = new RestRequest();
                if (_params != null)
                {
                    foreach (var kv in _params)
                    {
                        request.AddParameter(kv.Key, kv.Value);
                    }
                }
                var response = await client.ExecuteGetTaskAsync(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string content = response.Content;
                    var result = JsonConvert.DeserializeObject<T>(content);
                    success(result);
                }
                else
                {
                    error(response.StatusCode + " " + response.StatusDescription);
                }
            }
            catch (Exception ex)
            {
                //BuglyUtil.PostException(ex);
            }
        }
        public static async Task PostAsync<T, M>(string url, M model, Action<T> success, Action<string> error)
        {
            try
            {
                var client = GetRestClient(url);
                RestRequest request = new RestRequest();
                request.AddJsonBody(model);
                var response = await client.ExecutePostTaskAsync(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string content = response.Content;
                    var result = JsonConvert.DeserializeObject<T>(content);
                    success(result);
                }
                else
                {
                    error(response.StatusCode + " " + response.StatusDescription);
                }
            }
            catch (Exception ex)
            {
                //BuglyUtil.PostException(ex);
            }
        }
    }
}